package com.Liux.blog.controller;

import com.Liux.blog.entity.*;
import com.Liux.blog.service.ArticleService;
import com.Liux.blog.service.CommentsService;
import com.Liux.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class IndexController {

    @Autowired
    private UserService userService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CommentsService commentsService;

    @RequestMapping("/index")
    public ModelAndView index(ModelAndView modelAndView, HttpServletRequest request){
        String userId = "";
        Cookie[] cookies = request.getCookies();
        if(cookies == null){
            modelAndView.setViewName("login");
            return modelAndView;
        }
        for (Cookie c:
             cookies) {
            if(c.getName().equals("userId")){
                userId = c.getValue();
            }
        }
        System.out.println(userId);
        User user = userService.getUserById(userId);
        modelAndView.addObject("nikeName",user.getNikeName());
        modelAndView.addObject("signature",user.getSignature()==null?"还没有签名哦":user.getSignature());
        //排行榜
        List<Article> top6Article = articleService.getTop6Article();
        modelAndView.addObject("topArticle",top6Article);

        //请求文章
        List<ArticleVo> article = articleService.getArticle();
        modelAndView.addObject("articleList",article);
        modelAndView.setViewName("index");
        return modelAndView;

    }
    @GetMapping("/detail")
    public ModelAndView detail(@RequestParam("articleId")String aid, ModelAndView modelAndView){
        System.out.println(aid);
        Article articleById = articleService.getArticleById(aid);
        modelAndView.addObject("article",articleById);
        List<CommentsVo> list = commentsService.getArticleComments(aid);
        for (CommentsVo c:
             list) {
            System.out.println(c);
        }
        modelAndView.addObject("commentsList",list);
        modelAndView.addObject("commLength",list.size());
        modelAndView.setViewName("detail");
        return modelAndView;
    }
    @GetMapping("/fabu")
    public ModelAndView fabu(ModelAndView modelAndView){
        modelAndView.setViewName("fabu");
        return modelAndView;
    }


}
